package chat.fullduplex;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;

/**
 * This class contains the refactored loop that reads from the console. It is cleverly designed to
 * be used used by BOTH the client and the server. The main element of this is the addition of a 
 * "Local" interface to allow this shared object to call different "quit" logic for the server
 * and the client.
 * 
 * Note the use of a constructor to receive arguments / parameters that the run() loop needs. 
 * This step is necessary as the run():void method definition is fixed by Java (in the Runnable 
 * interface). If you do not respect this definition then the JVM will not find the method.
 * 
 * @author Justin Templemore
 */
public class ReadFromConsole implements Runnable 
{
	// the conection to the remote client/server
	private Socket remoteSocket;
	// The local end point that provides local-specific logic for quit
	private LocalChatEndPoint local;
	// Allows us to read lines of characters from the console (stdin)
	private BufferedReader inFromConsole;
	
	/**
	 * Create a Console Reader for the local endpoint over the provided socket.
	 * @param remoteSocket
	 * @param local
	 */
	public ReadFromConsole (Socket remoteSocket, LocalChatEndPoint local) 
	{
		this.remoteSocket = remoteSocket;	
		this.inFromConsole = new BufferedReader (new InputStreamReader(System.in));
		this.local = local;
	}
	@Override
	public void run() 
	{
		try 
		{
			// set up Readers and Writers to read and write text from/to the client
			PrintWriter outToClient = new PrintWriter (remoteSocket.getOutputStream(), true);
			String messageToClient;
			// continue until the socke is closed (readLine returns null)
			while (true) 
			{
				System.out.print("> ");
				messageToClient = inFromConsole.readLine();
				outToClient.println(messageToClient);
				if (messageToClient.equalsIgnoreCase ("Bye.")) 
				{
					local.quit();
					break;
				}
			}
		} 
		catch (IOException ioe) 
		{	
			// ignore
		}
		// We never actually get here because the thread never terminates. But because it
		// is a daemon thread the program will terminate without waiting for it to finish.
		System.out.println("Finished ReadFromConsole");
	}
}
